﻿using System;
using System.Configuration;
using Framework.Core;

namespace Framework.Remoting.Conventions
{
    public class HostConfiguration : ConfigurationSection, IEnvironments
    {
        [ConfigurationProperty("environments", IsDefaultCollection = false)]
        [ConfigurationCollection(typeof (Environments),
            AddItemName = "add")]
        public Environments Environments
        {
            get { return (Environments) base["environments"]; }
        }

        
        public IEnvironment GetEnvironment(EnvMode envMode)
        {
            var envs = (IEnvironments) base["environments"];
            var env = envs.GetEnvironment(envMode);

            if (env == null)
            {
                throw new EnvModeNotFoundException(string.Format(
                    "HostConfiguration was not found for environment : {0}", envMode));
            }

            return env;
        }

        
    }

    public class Environments : ConfigurationElementCollection, IEnvironments
    {
        
        public IEnvironment GetEnvironment(EnvMode envMode)
        {
            return (IEnvironment) BaseGet(envMode);
        }

        

        protected override ConfigurationElement CreateNewElement()
        {
            return new Environment();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((Environment) element).EnvMode;
        }
    }

    public class Environment : ConfigurationElement, IEnvironment
    {
        
        [ConfigurationProperty("mode")]
        public EnvMode EnvMode
        {
            get { return (EnvMode) Enum.Parse(typeof (EnvMode), this["mode"].ToString()); }
        }

        [ConfigurationProperty("port")]
        public int Port
        {
            get { return (int) this["port"]; }
        }

        [ConfigurationProperty("host")]
        public string Host
        {
            get { return (string) this["host"]; }
        }

        [ConfigurationProperty("binding")]
        public string BindingType
        {
            get { return (string) this["binding"]; }
        }

        
    }
}